package com.yc.sakuralxm.uestcscanning.tools

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Animatable
import android.net.Uri
import android.os.Handler
import android.text.TextUtils
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.TextView

import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.controller.BaseControllerListener
import com.facebook.drawee.controller.ControllerListener
import com.facebook.drawee.generic.RoundingParams
import com.facebook.drawee.interfaces.DraweeController
import com.facebook.drawee.view.SimpleDraweeView
import com.facebook.imagepipeline.image.ImageInfo
import com.facebook.imagepipeline.image.QualityInfo
import com.yc.sakuralxm.uestcscanning.R

import java.util.Calendar
import java.util.Date
import java.util.Locale
import kotlin.String.Companion

/**
 * Created by Administrator on 2016/8/13.
 */
object ViewUtil {

    /**
     * 宽不超过屏幕宽
     * 或者高度不超过屏幕高度
     *
     * @param sdv
     * @param url
     */
    //    public static void setImageURIWidth(SimpleDraweeView sdv, String url, float width, float heigth) {
    //        setImageURIWidth(sdv, url, width, heigth, 1);
    //    }

    //    public static void setImageURIWidth(SimpleDraweeView sdv, String url, float width, float heigth, int chuSu) {
    //        if (sdv != null) {
    //            if (TextUtils.isEmpty(url)) {
    //                url = DEFAULT_URL;
    //                return;
    //            }
    //            if (heigth > 0)
    //                sdv.setAspectRatio(width / heigth);
    //            int w = ((BaseAppContext)(sdv.getContext())).getScreenWidth() / chuSu;
    //            DraweeController controller = Fresco.newDraweeControllerBuilder()
    //                    .setUri(getApiUri(getWHPath(url, w, w)))
    //                    .setTapToRetryEnabled(true)   //点击重新加载图片
    //                    .build();
    //            sdv.setController(controller);
    //        }
    //    }
    private val DEFAULT_URL = "http://pic1.win4000.com/pic/1/cb/f33c967216.jpg"
    private val DEFAULT_URI = Uri.parse("http://pic1.win4000.com/pic/1/cb/f33c967216.jpg")


    val BASE_URL1 = "http://appfile.zm8090.com/"
    val BASE_URL = "http://obmrnutvx.bkt.clouddn.com/"

    fun setEtActionClick(et: EditText, view: View) {
        et.setOnEditorActionListener { paramTextView, paramInt, paramKeyEvent ->
            // || (paramKeyEvent != null && paramKeyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER))
            (paramInt == EditorInfo.IME_ACTION_DONE || paramInt == EditorInfo.IME_ACTION_NEXT) && view.performClick()
        }
    }

    fun setEtActionNext(et: EditText, nextEt: EditText) {
        et.setOnEditorActionListener(TextView.OnEditorActionListener { paramTextView, paramInt, paramKeyEvent ->
            if (paramKeyEvent != null && paramKeyEvent.keyCode == KeyEvent.KEYCODE_ENTER) {
                nextEt.requestFocus()
                return@OnEditorActionListener true
            }
            false
        })
    }

    fun inRangeOfView(view: View, ev: MotionEvent): Boolean {
        val location = IntArray(2)
        view.getLocationOnScreen(location)
        val x = location[0]
        val y = location[1]
        //        Log.i("realicing",String.format(Locale.CHINA,"---zzz---x = %d,y = %d,evx = %f,evy = %f,rawX = %f,rawY = %f,vw = %d,vh = %d",x,y,ev.getX(),ev.getY(),ev.getRawX(),ev.getRawY(),view.getWidth(),view.getHeight()));
        return !(ev.rawX < x || ev.rawX > x + view.width || ev.rawY < y || ev.rawY > y + view.height)
    }

    // msgListView是ListView控件
    // adapter是ListView绑定的Adapter，如果不方便直接使用，也可以通过ListView的getAdapter()方法获取到，前提是你已经绑定了适配器哦
    // 里面的参数就很熟悉了吧，其实这个方法的主要作用是选中listview的指定列，选中了，自然就得让这个item可见，自然就滚动咯
    fun setListViewSelectionLastIndex(lv: ListView) {
        lv.setSelection(lv.adapter.count - 1)
    }

    //方法二：
    // 这个就比较直接了
    fun setListViewSelectionBotoom(lv: ListView) {
        lv.setSelection(lv.bottom)
    }

    fun inflate(context: Context, layoutId: Int): View {
        return LayoutInflater.from(context).inflate(layoutId, null)
    }

    fun inflate(layoutId: Int, root: ViewGroup): View {
        return LayoutInflater.from(root.context).inflate(layoutId, root)
    }

    fun setImageURIApi(sdv: SimpleDraweeView?, imgUrl: String) {
        if (sdv != null && !TextUtils.isEmpty(imgUrl)) {
            sdv.setImageURI(getApiUri(imgUrl))
        }
    }

    fun getWHPath(url: String, w: Int, h: Int): String {
        return String.format(Locale.CHINA, "%s?imageView2/2/w/%d/h/%d", url, w, h)
    }

    @JvmOverloads
    fun setImageURIHead(sdv: SimpleDraweeView?, imgUrl: String, beiSu: Int = 1) {
        if (sdv != null) {
            if (TextUtils.isEmpty(imgUrl)) {
                sdv.setImageURI(DEFAULT_URL)
            } else {
                sdv.setImageURI(Uri.parse(getWHPath(imgUrl, beiSu * 50, beiSu * 50)))
            }
        }
    }

    fun setImageURILocal(sdv: SimpleDraweeView?, path: String) {
        if (sdv != null) {
            if (TextUtils.isEmpty(path)) {
                sdv.setImageURI(DEFAULT_URL)
            } else {
                sdv.setImageURI(Uri.parse("file://" + path))
            }
        }
    }

    fun pathToUrl(path: String): String {
        return "file://" + path
    }

    fun setImageURI(sdv: SimpleDraweeView?, imgUrl: String) {
        if (sdv != null) {
            if (TextUtils.isEmpty(imgUrl))
                sdv.setImageURI(DEFAULT_URL)
            else
                sdv.setImageURI(Uri.parse(imgUrl))
        }
    }

    /**
     * 自动适应比例
     *
     * @param sdv
     * @param imgUrl
     * //     * @param chuSu  最宽为屏幕的宽度除以chuSu
     * //
     */
    //    public static void setImageURIWidthAuto(SimpleDraweeView sdv, String imgUrl, int chuSu) {
    //        if (sdv != null) {
    //            if (TextUtils.isEmpty(imgUrl))
    //                setImageURIAuto(sdv, DEFAULT_URL);
    //            else {
    //                int w = ((BaseAppContext)(sdv.getContext())).getScreenWidth() / chuSu;
    //                setImageURIAuto(sdv, getWHPath(imgUrl, w, w));
    //            }
    //        }
    //    }


    //    public static void setImageURIAuto(final SimpleDraweeView sdv, final String imgUrl) {
    //        if (sdv != null) {
    //            if (TextUtils.isEmpty(imgUrl))
    //                setImageURIAuto(sdv, DEFAULT_URL);
    //            else {
    //                final ACache aCache = ((BaseAppContext)(sdv.getContext())).initaCache();
    //                Float ratio = (Float) aCache.getAsObject(imgUrl);
    //                if (ratio != null) {
    //                    sdv.setImageURI(getApiUri(imgUrl));
    //                    sdv.setAspectRatio(ratio);
    //                } else {
    //                    ControllerListener<ImageInfo> controllerListener = new BaseControllerListener<ImageInfo>() {
    //                        @Override
    //                        public void onFinalImageSet(String id, @Nullable final ImageInfo imageInfo, @Nullable Animatable anim) {
    //                            if (imageInfo == null || imageInfo.getHeight() <= 0) {
    //                                return;
    //                            }
    //                            Handler handler = sdv.getHandler();
    //                            if (handler != null)
    //                                handler.post(new Runnable() {
    //                                    @Override
    //                                    public void run() {
    //                                        Float aspectRatio = imageInfo.getWidth() * 1.0f / imageInfo.getHeight();
    //                                        sdv.setAspectRatio(aspectRatio);
    //                                        aCache.put(imgUrl, aspectRatio);
    ////                                        L.e(imgUrl + "," + imageInfo.getWidth() + "," + imageInfo.getHeight());
    //                                    }
    //                                });
    //                        }
    //                    };
    //                    sdv.setController(Fresco.newDraweeControllerBuilder().setControllerListener(controllerListener).setUri(Uri.parse(imgUrl)).build());
    //                }
    //            }
    //        }
    //    }

    fun recordImag(sdv: SimpleDraweeView?, imgUrl: String) {
        if (sdv != null && !TextUtils.isEmpty(imgUrl)) {
            val controllerListener = object : BaseControllerListener<ImageInfo>() {
                override fun onFinalImageSet(
                        id: String?,
                        imageInfo: ImageInfo?,
                        anim: Animatable?) {
                    if (imageInfo == null) {
                        return
                    }
                    val qualityInfo = imageInfo.qualityInfo
                    L.d(String.format(Locale.CHINA, "Final image received!Size %d x %d, Quality level %d, good enough: %b, full quality: %b",
                            imageInfo.width,
                            imageInfo.height,
                            qualityInfo.quality,
                            qualityInfo.isOfGoodEnoughQuality,
                            qualityInfo.isOfFullQuality))
                    val path: String
                    if (imgUrl.startsWith("file://")) {
                        path = imgUrl.substring(7)
                    } else {
                        path = imgUrl
                    }
                    //                    fileMap.put(path, File.getInstance(File.IMG, imageInfo.getWidth(), imageInfo.getHeight()));
                }

                override fun onIntermediateImageSet(id: String?, imageInfo: ImageInfo?) {
                    L.d("Intermediate image received")
                }

                override fun onFailure(id: String?, throwable: Throwable?) {
                    L.e("Error loading " + id!!)
                }
            }

            val uri = Uri.parse(imgUrl)
            val controller = Fresco.newDraweeControllerBuilder()
                    .setControllerListener(controllerListener)
                    .setUri(uri)
                    // other setters
                    .build()
            sdv.controller = controller
        }
    }


    fun setTvTime(tv: TextView, time: Long) {
        val thisTime = secTimeToMillstime(time)

        val date = Date(thisTime)


        val today = Calendar.getInstance()    //今天

        //  Calendar.HOUR——12小时制的小时数 Calendar.HOUR_OF_DAY——24小时制的小时数
        today.set(Calendar.HOUR_OF_DAY, 0)
        today.set(Calendar.MINUTE, 0)
        today.set(Calendar.SECOND, 0)

        val yesterday = Calendar.getInstance()    //昨天

        yesterday.set(Calendar.YEAR, today.get(Calendar.YEAR))
        yesterday.set(Calendar.MONTH, today.get(Calendar.MONTH))
        yesterday.set(Calendar.DAY_OF_MONTH, today.get(Calendar.DAY_OF_MONTH) - 1)
        yesterday.set(Calendar.HOUR_OF_DAY, 0)
        yesterday.set(Calendar.MINUTE, 0)
        yesterday.set(Calendar.SECOND, 0)

        val current = Calendar.getInstance()
        current.time = date
        if (time == 0L) {
            tv.text = ""
        } else if (current.after(today)) {
            tv.text = String.format("%tR", thisTime)
        } else if (current.before(today) && current.after(yesterday)) {
            tv.text = String.format("昨天 %tR", thisTime)
        } else if (current.get(Calendar.YEAR) == today.get(Calendar.YEAR)) {
            tv.text = String.format(Locale.CHINA, "%d月%d日", current.get(Calendar.MONTH) + 1, current.get(Calendar.DAY_OF_MONTH))
        } else {
            tv.text = String.format(Locale.CHINA, "%tD%n", date)//7/14/13
            //            tv.setText(String.format(Locale.CHINA,"%ty%n年%d月%d日",date, current.get(Calendar.MONTH)+1, current.get(Calendar.DAY_OF_MONTH)));//03年7月14日
        }
    }

    fun setTvTimeText(tv: TextView, time: Long) {
        if (time == 0L) {
            tv.text = ""
        } else {
            tv.text = String.format("%tR", secTimeToMillstime(time))

        }
    }

    fun setTvText(tv: TextView, time: Long) {
        if (time == 0L) {
            tv.text = ""
        } else {
            tv.text = String.format("%tF\r\r%tR", secTimeToMillstime(time), secTimeToMillstime(time))
        }

    }

    fun setTvText(tv: TextView, msg: String, defaultMsg: String) {
        tv.text = ""
        tv.append(if (TextUtils.isEmpty(msg)) defaultMsg else msg)
    }

    fun setTvText(firstMsg: String, tv: TextView, msg: String) {
        tv.text = if (TextUtils.isEmpty(firstMsg)) "" else firstMsg
        tv.append(if (TextUtils.isEmpty(msg)) "" else msg)
    }

    fun setTvTextShow(firstMsg: String, tv: TextView, msg: String) {
        if (TextUtils.isEmpty(msg) || TextUtils.isEmpty(firstMsg)) {
            tv.visibility = View.GONE
        } else {
            tv.visibility = View.VISIBLE
        }
        tv.text = if (TextUtils.isEmpty(firstMsg)) "" else firstMsg
        tv.append(if (TextUtils.isEmpty(msg)) "" else msg)
    }

    fun setTvText(tv: TextView, msg: String?) {
        tv.text = ""
        if (msg != null)
            tv.append(msg)
    }

    fun setTvEdText(tv: EditText, msg: String?) {
        tv.setText("")
        if (msg != null)
            tv.append(msg)
    }

    fun appendTvText(tv: TextView, msg: String?) {
        if (msg != null)
            tv.append(msg)
    }

    fun secTimeToMillstime(t: Long): Long {
        return if (t < 10000000000L) {
            t * 1000
        } else
            t
    }
    //
    //    public static View addViewBefore(View view, int viewId, int marginId) {
    //////       ((BaseAppContext)(sdv.getContext())).showToastCenterShort("添加一个元素",);
    ////        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    ////        int bottom = view.getContext().getResources().getDimensionPixelOffset(R.dimen.margin);
    ////        int margin = view.getContext().getResources().getDimensionPixelOffset(marginId);
    ////        lp.setMargins(margin, 0, margin, bottom);
    ////        LinearLayout parent = (LinearLayout) view.getParent();
    ////        View newView = LayoutInflater.from(view.getContext()).inflate(viewId, null);
    ////        int index = parent.indexOfChild(view);
    ////        parent.addView(newView, index, lp);
    ////        return newView;
    //    }

    //    public static View addViewBehind(View view, int viewId, int marginId) {
    ////       ((BaseAppContext)(sdv.getContext())).showToastCenterShort("添加一个元素",);
    //        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    //        int bottom = view.getContext().getResources().getDimensionPixelOffset(R.dimen.margin);
    //        int margin = view.getContext().getResources().getDimensionPixelOffset(marginId);
    //        lp.setMargins(margin, 0, margin, bottom);
    //        LinearLayout parent = (LinearLayout) view.getParent();
    //        View newView = LayoutInflater.from(view.getContext()).inflate(viewId, null);
    //        parent.addView(newView, lp);
    //        return newView;
    //    }

    fun getItem(color: String, content: String): String {
        return String.format("<font color=\'#%s\'>%s</font>", color, content)
    }

    fun getApiUri(path: String): Uri {
        return Uri.parse(getApiPath(path))
    }

    fun getApiPath(path: String): String {
        val result = if (!TextUtils.isEmpty(path) && path.startsWith("http://")) path else BASE_URL + path
        //        if(result.startsWith(BASE_URL1)){
        //            result =  result.replaceFirst(BASE_URL1,BASE_URL);
        //        }
        L.i("getApiPath " + result)
        return result
    }

    fun getNoApiPath(path: String?): String? {
        val result = if (path != null && path.startsWith(BASE_URL)) path.substring(BASE_URL.length) else path
        L.i("getNoApiPath " + result!!)
        return result
    }


    /**
     * 头像显示圆边
     *
     * @param simpleDraweeView
     */
    fun setSdvAsCircle(simpleDraweeView: SimpleDraweeView, dimenesionId: Int) {
        val roundingParams = RoundingParams.asCircle()
        roundingParams.setBorder(Color.WHITE, simpleDraweeView.resources.getDimension(dimenesionId))
        simpleDraweeView.hierarchy.roundingParams = roundingParams
    }

    /**
     * 头像显示圆边
     *
     * @param simpleDraweeView
     */
    fun setSdvAsCircle(simpleDraweeView: SimpleDraweeView) {
        val roundingParams = RoundingParams.asCircle()
        simpleDraweeView.hierarchy.roundingParams = roundingParams
    }

    /**
     * 头像显示圆角
     *
     * @param simpleDraweeView
     */
    fun setSdvAsYuanJiao(simpleDraweeView: SimpleDraweeView, dimenesionId: Int) {
        val roundingParams = RoundingParams.fromCornersRadius(simpleDraweeView.resources.getDimension(dimenesionId))
        simpleDraweeView.hierarchy.roundingParams = roundingParams
    }

    fun toggleVisibility(view: View): Int {
        val v = if (view.visibility == View.VISIBLE) View.INVISIBLE else View.VISIBLE
        view.visibility = v
        return v
    }

    fun setTvSex(tv: TextView, sex: String) {
        //        if (tv != null) {
        //            tv.setText(StringUtil.equals(sex, "0") ? "女" : "男");
        //        }
    }


}
